﻿using System;
using System.Collections.Generic;

public delegate void DeleWithParams(params object[] args);

/// <summary>
/// 事件类型
/// </summary>
public enum MyEvent
{
    日志,
}

/// <summary>
/// 事件管理器
/// </summary>
public class MyEventManager
{
    public static MyEventManager Instance { get { return Singleton<MyEventManager>.Instance; } }

    /// <summary>
    /// 所有事件字典
    /// </summary>
    private Dictionary<MyEvent, MyEventUnit> eventDict = new Dictionary<MyEvent, MyEventUnit>();

	/// <summary>
	/// 注册事件
	/// </summary>
	/// <param name="myEvent">事件类型</param>
	/// <param name="dele">对应方法</param>
	public void Register(MyEvent myEvent, DeleWithParams dele)
	{
		if (eventDict.ContainsKey(myEvent))
		{
			eventDict[myEvent].Register(dele);
		}
		else
		{
			MyEventUnit eventUnit = new MyEventUnit();
			eventUnit.Register(dele);
			eventDict.Add(myEvent, eventUnit);
		}
	}

	/// <summary>
	/// 注销事件
	/// </summary>
	/// <param name="myEvent">事件类型</param>
	/// <param name="dele">对应方法</param>
	public void UnRegister(MyEvent myEvent, DeleWithParams dele)
	{
		if (eventDict.ContainsKey(myEvent))
			eventDict[myEvent].UnRegister(dele);
		else
			throw new Exception("MyEventManager.UnRegister没有事件可注销 :" + myEvent.ToString());
	}

	/// <summary>
	/// 广播事件
	/// </summary>
	/// <param name="myEvent">事件类型</param>
	/// <param name="args">事件参数</param>
	public void Broadcast(MyEvent myEvent, params object[] args)
	{
		if (eventDict.ContainsKey(myEvent))
			eventDict[myEvent].Broadcast(args);
	}
}

/// <summary>
/// 事件单位
/// </summary>
public class MyEventUnit : IDisposable
{
	private event DeleWithParams myEvent = null;

	public void Register(DeleWithParams dele)
	{
		myEvent += dele;
	}

	public void UnRegister(DeleWithParams dele)
	{
		myEvent -= dele;
	}

	public void Broadcast(params object[] args)
	{
		if (myEvent != null)
			myEvent(args);	
	}

	#region IDisposable implementation

	public void Dispose ()
	{
		myEvent = null;
	}

	#endregion
}